/* author = Tam nguyen */

package com.applink.sell_proof;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.constant.ItemStatus;
import com.applink.sell_proof.fragment.InvoiceBrieftFragment;
import com.applink.sell_proof.fragment.InvoiceDetail;
import com.applink.sell_proof.fragment.InvoiceDetailExt;
import com.applink.sell_proof.model.Claim;
import com.applink.sell_proof.model.ClaimImage;
import com.applink.sell_proof.model.MyImage;
import com.applink.sell_proof.urlimageviewhelper.UrlPagerClaimAdapter;

public class DetailClaim extends BaseClaim {

	public static final String TAG = "DetailClaim";

	public static final String CLAIM_STATUS = "claimstatus";
	public static final String CLAIM_LOCALID = "claimlocalid";
	// public static final String CLAIM_ID = "claimid";

	// private long mClaimId = 0;

	private String mLocalClaimId = "";
	private RelativeLayout layoutGallery;
	private ImageView imgView;

	private static final int SHOW_IMAGE = 0;
	private int isDraft = -1;
	

	@Override
	protected void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		setTitle(getString(R.string.viewclaim));
		showloading();
		DataHelper.getInstance().addObserver(this);
		DataHelper.getInstance().getClaimDetail(mLocalClaimId);
	}

	@Override
	protected boolean ClaimDetailSelected() {
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();

		transaction.add(R.id.invoice_container,
				InvoiceDetailExt.newInstance(isDraft()), InvoiceDetail.TAG);

		transaction.setCustomAnimations(R.anim.slide_left_right,
				R.anim.slide_right_left);

		transaction.commit();

		return true;
	}

	@Override
	protected void initView() {
		super.initView();
		
		// if it's not allow to take new picture ==> disable the took picture
		if (!isDraft()) {
			imgSelectGallery.setVisibility(View.GONE);
			imgTakePhoto.setVisibility(View.GONE);
			imgDeleteAllImages.setVisibility(View.GONE);
			imgDeleteImage.setVisibility(View.GONE);	
		}
		
		if(isDraft()){
			//layoutGallery.setVisibility(View.VISIBLE);
			imgSelectGallery.setVisibility(View.VISIBLE);
			imgTakePhoto.setVisibility(View.VISIBLE);
			imgDeleteAllImages.setVisibility(View.VISIBLE);
			imgDeleteImage.setVisibility(View.VISIBLE);			
		}

		// if (mLocalClaimId.equals("") == 0) {
		// mClaimId = getIntent().getLongExtra(DetailClaim.CLAIM_ID, 0);
		// }

		if (mLocalClaimId.equals("")) {
			mLocalClaimId = getIntent().getStringExtra(
					DetailClaim.CLAIM_LOCALID);
		}
	}

	/**
	 * determine that we're currently in draft mode or not
	 * 
	 * @return
	 */
	private boolean isDraft() {

		if (isDraft != -1)
			return isDraft == 0 ? false : true;

		Intent i = getIntent();
		String ClaimStatus = i.getStringExtra(DetailClaim.CLAIM_STATUS);

		if (!ClaimStatus.equals("Draft"))
			isDraft = 0;
		else
			isDraft = 1;

		return isDraft == 0 ? false : true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.w(TAG, "onCreateOptionsMenu");

		mReloadMenu = true;

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		if (!mReloadMenu)
			return super.onPrepareOptionsMenu(menu);

		if (!isDraft()) {

			menu.removeItem(R.id.menu_submit_claim);
			menu.removeItem(R.id.menu_save_claim);

			MenuItem add = menu.findItem(R.id.menu_add_product);
			if (add != null)
				add.setVisible(false);

			MenuItem header = menu.findItem(R.id.menu_header);
			if (header != null)
				header.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		} else {
			MenuItem submit = menu.findItem(R.id.menu_submit_claim);
			MenuItem save = menu.findItem(R.id.menu_save_claim);

			submit.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
			save.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);

			MenuItem delete = menu.add(Menu.NONE, R.id.menu_delete_item,
					Menu.FLAG_APPEND_TO_GROUP, R.string.delete);

			delete.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
		}

		Log.w(TAG, "onPrepareOptionsMenu");

		mReloadMenu = false;

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_delete_item:

			showloading();
			DataHelper.getInstance().addObserver(this);
			DataHelper.getInstance().deleteClaim(mLocalClaimId);
			return true;
		default:
			super.onOptionsItemSelected(item);
			break;
		}

		return false;
	}

	@Override
	protected void onResume() {
		super.onResume();
		DataHelper.getInstance().addObserver(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		DataHelper.getInstance().deleteObserver(this);
	}

	@Override
	public void update(Observable observable, Object data) {

		hideloading();

		DataResult result = (DataResult) data;

		switch (result.getMethodName()) {
		case getClaimDetail:
			Claim claim = (Claim) result.getData();

			mProducts = claim.getProducts();

			mClaimImages = claim.getImages();

			InvoiceBrieftFragment brieftInvoice = (InvoiceBrieftFragment) getSupportFragmentManager()
					.findFragmentByTag("InvoiceBrieftFragment");

			if (brieftInvoice == null)
				break;

			brieftInvoice.setClaimHeader(claim);

			if (mClaimImages.size() >= 1
					&& mClaimImages.get(0).getImageLocation().toString()
							.length() != 0) {

				imgNoPhoto.setVisibility(View.GONE);
				mViewPager.setVisibility(View.VISIBLE);
				mHandler.sendEmptyMessage(SHOW_IMAGE);
			}

			if (!isDraft()) {
				brieftInvoice.disableEdit();
			}

			// if (Constant.CHECK_OPPORTUNITY) {
			// invalidateOptionsMenu();
			// }

			break;
		default:
			super.update(observable, data);
			break;
		}
	}

	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_IMAGE:

				UrlPagerClaimAdapter pagerAdapter = new UrlPagerClaimAdapter(
						mContext, new ArrayList<MyImage>(mClaimImages));
				mViewPager.setAdapter(pagerAdapter);
				break;

			default:
				break;
			}
			return false;
		}
	});

	@Override
	protected void createClaim(Claim claim) {
		updateClaim(claim, ItemStatus.SUBMITTED);
	}

	@Override
	protected void saveClaim(Claim claim) {
		updateClaim(claim, ItemStatus.DRAFT);
	}		

	private void updateClaim(Claim claim, String status) {

		Claim custom = claim;

		// assign the opportunity status again
		custom.setStatus(status);

		// set Id for claim
		// custom.setId(mClaimId);

		custom.setLocalId(mLocalClaimId);

		List<ClaimImage> updateImages = new ArrayList<ClaimImage>(mClaimImages);
		updateImages.addAll(mRemoveClaimImages);

		custom.setImages(updateImages);
		DataHelper.getInstance().updateClaim(custom);

		showloading();
	}
}
